<?php


namespace GordenSong\Support;


use GordenSong\Utils\RuleUtil;
use Webmozart\Assert\Assert;

abstract class TableValidator extends Validator
{
	/** @var null|string */
	protected $connection = null;

	/** @var string */
	protected $table = null;

	/**
	 * @throws \Doctrine\DBAL\Schema\SchemaException
	 * @throws \GordenSong\Exceptions\TableNotExistException
	 */
	public function __construct()
	{
		$this->connection = $this->connection ?: config('database.default');

		Assert::notNull($this->table);
		Assert::notNull($this->connection);

		$this->rules = RuleUtil::mergeManyRules($this->tableRules(), $this->rules());

		parent::__construct();
	}

	public function getTable(): string
	{
		return $this->table;
	}

	public function getConnection(): ?string
	{
		return $this->connection;
	}

	/**
	 * @throws \GordenSong\Exceptions\TableNotExistException
	 * @throws \Doctrine\DBAL\Schema\SchemaException
	 */
	public function tableRules(): array
	{
		return RuleRepository::getRules($this->getConnection(), $this->getTable());
	}
}
